package com.hdl.client;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.List;

/**
 * 使用协处理器解除用户之间的关系，uid1 解除 uid2关系， uid2 同时 解除 uid1 关系
 *
 */
public class DeleteRelationsProcessor extends BaseRegionObserver {

    /**
     * 删除关系数据之后触发解除另一方与自己的关系n
     */
    @Override
    public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit, Durability durability) throws IOException {
        // 获取表
        HTableWrapper relations = (HTableWrapper) e.getEnvironment().getTable(TableName.valueOf("user_relations"));

        //获取删除的行rowKey
        byte[] row = delete.getRow();

        //获取到firends下所有的cell
        List<Cell> friends = delete.getFamilyCellMap().get(Bytes.toBytes("friends"));

        for (Cell friend : friends) {
            //准备get对象
            byte[] bytes = CellUtil.cloneQualifier(friend);
            //指定查询某个列族或者列
            byte[] family = Bytes.toBytes("friends");

            // 创建GET对象
            Get get = new Get(bytes);
            //指定查询某个列族或者列
            get.addFamily(family);
            get.addColumn(family, row);
            // 执行查询
            Result result = relations.get(get);
            if (result.rawCells().length == 0){
                continue;
            }
            Delete delete1 = new Delete(bytes);
            delete1.addColumn(family, row);
            relations.delete(delete1);
        }
        relations.flushCommits();
        relations.close();
    }
}
